How to disable command buttons in ASPxGridView

ASP.NET Team Blog
13 January 2009
Update: Please check this code central example for a better approach: How to use ASPxCheckBox in DataItemTemplate to emulate a selection

Check out this quick tip on how to disable the Insert, Edit and Delete command buttons in the ASPxGridView.

We've also created a new ASPxGridView event to simply the approach described above. But more on that later.

Scenario

You've enabled edit/insert/delete functionality for your grid, however, you need to disable it for certain rows.

Solution

First, we should dynamically check which rows need to be disabled. Then we'll use the HtmlCommandCellPrepared event because it allows you to change the settings of individual command column cells. For example, this code below will hide the 'New' button and disable the selection check box for every other row:

protected void ASPxGridView1_HtmlCommandCellPrepared(object sender, ASPxGridViewTableCommandCellEventArgs e)
{
    if (e.CommandCellType == DevExpress.Web.ASPxGridView.GridViewTableCommandCellType.Data)
    {
        // odd row
        if (e.VisibleIndex % 2 == 0)
        { 
            e.Cell.Controls[1].Visible = false;  // hide the New button
            ((WebControl)e.Cell.Controls[3]).Attributes["disabled"] = "true"; // disable the selection checkbox
        }
    }
}

You can download and see a live demo of this code at Code Central: How to customize command buttons in individual rows

New Event For Easier Approach

While the approach described above is good, the R&D team wanted to improve access to the command buttons at runtime. So a new event was implemented for the upcoming DXperience 2009 Volume 1 release. The new CommandButtonInitialize event allows you to change command button controls visibility and also enable/disable them easily. For example, the code below shows how to hide every third "Select" button and disable every second 'Select" button:

protected void ASPxGridView1_CommandButtonInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCommandButtonEventArgs e)
{
    if (e.Button.ButtonType != DevExpress.Web.ASPxGridView.ColumnCommandButtonType.Select) return;
    e.Visible = e.VisibleIndex % 3 != 1;
    e.Enabled = e.VisibleIndex % 2 != 1;
}

DXperience? What's That?

DXperience is the .NET developer's secret weapon. Get full access to a complete suite of professional components that let you instantly drop in new features, designer styles and fast performance for your applications. Try a fully-functional version of DXperience for free now: http://www.devexpress.com/Downloads/NET/

Free DevExpress Products - Get Your Copy Today

The following free DevExpress product offers remain available. Should you have any questions about the free offers below, please submit a ticket via the DevExpress Support Center at your convenience. We'll be happy to follow-up.
No Comments

Please login or register to post comments.